package org.wenhua.preloadlib.activity

import android.content.Context
import android.content.Intent
import android.os.Looper
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import kotlin.reflect.KClass

/**
 * ActivityPreloadManager.preload
 * 预加载处理跳转页布局View，添加到自定义View[BasePreloadView]中
 *
 * 跳转到Activity，执行生命周期，将自定义基类View，在setContentView方法添加、渲染到屏幕
 * demo应用在：HybridArcPro# MainBasePreloadActivity.kt  CMBCTabFragment.kt
 */
object ActivityPreloadManager {

    /** View预加载 */
    fun preload(intent: Intent, context: Context, resId: Int) {
        // 执行缓存时，须判断缓存中不存在
        val preloadView:BasePreloadView? = BasePreloadView.getVal(intent)
        if (preloadView != null) {
            throw IllegalStateException("Error:布局View重复加载..." )
        }

        val clazz:Class<PreloadBundleView> = PreloadBundleView::class.java
        Looper.myQueue().addIdleHandler {
            // 不占用UI线程，空闲时执行, 反射获取布局实例并缓存
            val instance = clazz.getConstructor(Context::class.java).newInstance(context)
            instance.onCreatedInit(resId)
            // 缓存
            BasePreloadView.putVal(intent, instance)
            true
        }
    }

    fun <T: Intent>removePreloadLayoutView (view: T) {
        BasePreloadView.removeVal(view)
    }
}


/** Activity#onCreate方法中执行（兜底加载View）。
 * 缓存中获取不到时，通过 KClass<T> 反射获取实例 */
fun <T : BasePreloadView> KClass<T>.createView(
    intent: Intent,
    context: Context,
    resId: Int
): T {

    var preLoadView: BasePreloadView? = BasePreloadView.getVal(intent)
    if (preLoadView == null) {
        preLoadView = java.getConstructor(Context::class.java).newInstance(context)
        preLoadView!!.onCreatedInit(resId)
        BasePreloadView.putVal(intent, preLoadView)
    } else {
        if (preLoadView.parent != null && preLoadView.parent is ViewGroup) {
            (preLoadView.parent as ViewGroup).removeView(preLoadView)
        }
    }

    return preLoadView as T
}



/** 继承FrameLayout自定义FrameLayout，
 * 将布局子View添加到自定义FrameLayout */
abstract class BasePreloadView(context: Context) : FrameLayout(context) {
    companion object {
        private val CACHE_VIEWS:MutableMap<String, BasePreloadView> = mutableMapOf<String, BasePreloadView>()

        fun getVal (intent:Intent): BasePreloadView? = if (CACHE_VIEWS[intent.toString()] == null) null else CACHE_VIEWS[intent.toString()] as BasePreloadView

        fun <T: BasePreloadView> putVal (intent: Intent, value:T) {
            CACHE_VIEWS[intent.toString()] = value
        }

        fun <T: Intent> removeVal(intent: T) {
            CACHE_VIEWS.remove(intent.toString())
        }


    }


    /**
     * 添加resId-View到当前自定义View
     */
    open fun onCreatedInit(resId: Int) {
        LayoutInflater.from(context).inflate(resId, this) // 添加到当前自定义的ViewGroup
    }

}